package com.java.nio;

import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author jl
 * Created on 2020/9/26
 */
public class NIOFileChannel01 {

    public static void main(String[] args) throws IOException {
        String str = "hello,中国";
        // 创建一个输出流->channel
        FileOutputStream fileOutputStream = new FileOutputStream("d://file01.txt");
        // 通过fileOutputStream获取对应的FileChannel,FileChannel的真实类型的FileChannelImpl
        FileChannel fileChannel = fileOutputStream.getChannel();
        // 创建一个缓冲区ByteBuffer
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        // 将str放入缓冲区中
        byteBuffer.put(str.getBytes());
        // 对ByteBuffer进行读写切换
        byteBuffer.flip();
        // 将byteBuffer数据写入channel中
        fileChannel.write(byteBuffer);

        fileOutputStream.close();
    }
}
